<?php

namespace app\common\service;

use app\admin\model\KnscyUserBind;
use app\admin\model\KnscyUsers;
use think\facade\Request;

class UserService
{
    public static function getTestUser(){
        $data =  KnscyUsers::field('id,nickname,username,mobile,head_img,ishexiao,last_login_time,uniacid')->find( 1);
        if(empty($data['head_img'])){
            $data['head_img'] = tomedia("addons/kbwdl_nickscenery/public/images/get_avatar.png");
        }else{
            $data['head_img'] = get_full_url($data['head_img']) ;
        }
        return $data;
    }
    public static function checkOpenidBindUser()
    {
        $token = '';
        $token_str = Request::header()['authorization'] ?? false;
        if($token_str){
            $bears = explode(' ', $token_str);
            $token = $bears[1] ?? '';
        }
        if($token == '25dbc1ef2ddd1c403b58e1c05afcdd1d'){
            return self::getTestUser();
        }
        $openid = WeginService::openid();
        $bind = KnscyUserBind::where(['openid'=>$openid,'token'=>$token])->find();
        if(empty($bind)){
            return false;
        }
        $data =  KnscyUsers::field('id,nickname,username,mobile,head_img,ishexiao,last_login_time,uniacid')->find($bind->user_id);
        //用户信息存在时候才处理头像
        if($data && isset($data['head_img'])){
            $data['head_img'] = get_full_url($data['head_img']);
        }

        return $data;
    }
    /**
     * h5 通过post传递 openid
     * 小程序通过 $_W里面的openid
     * @param $openid
     * @return mixed
     */
    public static function getUserIdByOpenid($openid = ''){
        if(empty($openid)){
            $openid = request()->post('openid');
        }
        if(empty($openid)){
            $openid = WeginService::openid();
        }
        if(empty($openid)){ return 0; }
        //没有openid
        $bind = KnscyUserBind::where(['openid'=>$openid])->find();
        if(empty($bind)){
            $user = KnscyUsers::create([
                'uniacid'=> WeginService::getUniacid(),
                'username'=>$openid,
                'nickname'=>'微信用户',
                'status'=>0,
            ]);
            KnscyUserBind::create([
                'openid'=>$openid,
                'uniacid'=> WeginService::getUniacid(),
                'user_id'=> $user->id,
                'bind_type'=> 'wxapp',
            ]);
        }else{
            $user = KnscyUsers::find($bind->user_id);
            if(empty($user)){
                $user = KnscyUsers::create([
                    'uniacid'=> WeginService::getUniacid(),
                    'username'=>$openid,
                    'nickname'=>'微信用户',
                    'status'=>0,
                ]);
                $bind->user_id = $user->id;
                $bind->save();
            }
        }
        return $user->id ?? 0;
    }
}